package com.example.pixelyear.ui.act

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.view.KeyEvent
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.viewpager2.widget.ViewPager2
import com.example.pixelyear.Interface.MainViewPageClickListener
import com.example.pixelyear.Interface.OnSelectColorListener
import com.example.pixelyear.R
import com.example.pixelyear.adapter.MainViewPage2Adapter
import com.example.pixelyear.bean.DateBean
import com.example.pixelyear.bean.EventTags
import com.example.pixelyear.bean.MessageEvent
import com.example.pixelyear.bean.YearBean
import com.example.pixelyear.sql.NoteSqlUtils
import com.example.pixelyear.sql.RecordSqlUtils
import com.example.pixelyear.ui.base.BaseActivity
import com.example.pixelyear.utils.*
import com.example.pixelyear.utils.dialog.AddDateDialog
import com.example.pixelyear.utils.extension.setOnDoubleClickListener
import com.socks.library.KLog
import kotlinx.android.synthetic.main.activity_main.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class MainActivity : BaseActivity() {
    private var lastChoosePosition = -1
    private var lastYear = 0
    private var lastMonth = 0
    private var lastDay = 0
    private var nowMonthIndex = -1
    private var apk: String = ""

    private val recordSql by lazy {
        RecordSqlUtils.getInstance(mActivity)
    }

    private val noteSql by lazy {
        NoteSqlUtils.getInstance(mActivity)
    }

    private val mAdapter by lazy {
        MainViewPage2Adapter(mActivity)
    }

    private val colorDialog by lazy {
        AddDateDialog(mActivity)
    }

    override fun getLayoutResID(): Int {
        return R.layout.activity_main
    }

    override fun initView(bundle: Bundle?) {
        EventBus.getDefault().register(this)
        Main_Page.adapter = mAdapter
    }

    override fun initData() {
        initTime()
        requestSdPermission(11) {}
        FunctionUtils.checkUpdate(mActivity) {
            apk = it
            requestSdPermission {
                FunctionUtils.downloadApk(mActivity, it)
            }
        }
    }

    override fun initListener() {
        mAdapter.setOnListener(object : MainViewPageClickListener {
            override fun onClick(
                year: Int,
                month: Int,
                day: Int,
                color: Int,
                hasNote: Boolean,
                position: Int,
                mood: String?
            ) {
                lastYear = year
                lastMonth = month
                lastDay = day
                lastChoosePosition = position
                if (hasNote || !mood.isNullOrEmpty()) {
                    YxsDisplay.toNote(mActivity, Bundle().also {
                        it.putInt("y", year)
                        it.putInt("m", month)
                        it.putInt("d", day)
                        it.putInt("c", color)
                        it.putString("mood", mood)
                    }, requestCode = 1)
                } else {
                    colorDialog.show(year, month, day, color)
                }
            }

            override fun onLongClick(
                year: Int,
                month: Int,
                day: Int,
                color: Int,
                hasNote: Boolean,
                position: Int,
                mood: String?
            ) {
                KLog.e("yxs", "长按事件")
                TipsDialogUtils.showSureCancelDialog(
                    mActivity,
                    content = "是否删除 $year-$month-$day 这天的记录？"
                ) {
                    recordSql?.delete(year, month, day)
                    val list = mAdapter.getItemAtPosition(position)
                    var index = -1
                    kotlin.run {
                        list.list.forEachIndexed { i, dateBean ->
                            if (dateBean.year == year && month == dateBean.month && day == dateBean.day) {
                                index = i
                                return@run
                            }
                        }
                    }
                    if (index != -1)
                        list.list.removeAt(index)
                    mAdapter.updateItem(position, list)
                }
            }
        })

        colorDialog.setOnSelectColorListener(object : OnSelectColorListener {
            override fun OnSelect(
                year: Int,
                month: Int,
                day: Int,
                color: Int,
                chooseColor: Int,
                mood: String
            ) {
                if (color == -1) {
                    YxsDisplay.toNote(mActivity, Bundle().also {
                        it.putInt("y", year)
                        it.putInt("m", month)
                        it.putInt("d", day)
                        it.putInt("c", chooseColor)
                    }, requestCode = 1)
                } else {
                    //Color.parseColor("#00FFFFFF") xor 取消取对比色
                    val bean = DateBean(
                        month,
                        year,
                        day,
                        color,
                        Utils.colorDepth(color),
                        mood
                    )
                    recordSql?.addData(bean)
                    if (lastChoosePosition != -1) {
                        val list = mAdapter.getItemAtPosition(lastChoosePosition)
                        add(list.list, bean)
                        KLog.e("yxs", "添加的数据：" + bean.toString() + "===" + list.list.size)
                        mAdapter.updateItem(lastChoosePosition, list)
                    }
                }
            }

            override fun OnEdit() {
                YxsDisplay.toEditColor(mActivity)
            }
        })

        Main_Page.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                with(mAdapter.getItemAtPosition(position)) {
                    Main_Year.text = "${year}年"
                    Main_Month.text = "${month}月"
                    if (list.isNullOrEmpty()) {
                        list = recordSql?.getData(year, month)
                        DefaultHandler.getInstance().postDelayed({
                            mAdapter.updateItem(position, this)
                        }, 100)
                    }
                }
            }
        })

        Main_Up.setOnDoubleClickListener {
            if (Main_Page.currentItem != nowMonthIndex && nowMonthIndex != -1) {
                setCurrent(nowMonthIndex)
            }
        }

        Main_Setting.setOnDoubleClickListener {
            YxsDisplay.toSetting(mActivity)
        }

        Main_YearView.setOnDoubleClickListener {
            YxsDisplay.toYearView(mActivity, 1)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1) {
            if (resultCode == Constant.EDIT_NOTE_RESULT) {
                val exists = noteSql?.getData("$lastYear-$lastMonth-$lastDay")
                val oneData = recordSql?.getOneData(lastYear, lastMonth, lastDay)
                KLog.e("yxs", "接受到返回：${oneData == null}===$exists")
                if (oneData != null) {
                    oneData.note =
                        exists?.data?.let { if (it.length > 30) it.substring(0, 30) else it } ?: ""
                    val itemAtPosition = mAdapter.getItemAtPosition(lastChoosePosition)
                    add(itemAtPosition.list, oneData)
                    mAdapter.updateItem(lastChoosePosition, itemAtPosition)
                }
            } else if (resultCode == Constant.YEAR_VIEW_RESULT) {
                val y = data?.getIntExtra("year", 0) ?: 0
                val m = data?.getIntExtra("month", 0) ?: 0
                if (y != 0 && m != 0) {
                    kotlin.run {
                        mAdapter.getList().forEachIndexed { index, yearBean ->
                            if (yearBean.year == y && m == yearBean.month) {
                                setCurrent(index)
                                return@run
                            }
                        }
                    }
                } else Utils.showToast("出现了未知错误，请稍后重试～")
            }
        }
    }

    private fun add(list: MutableList<DateBean>, data: DateBean) {
        KLog.e("yxs", "添加列表是否为空：${list.isEmpty()}")
        if (list.isNotEmpty()) {
            val filter = list.filter {
                it.month == data.month && it.year == data.year && it.day == data.day
            }
            KLog.e("yxs", "是否已经有这天的数据：${filter.isEmpty()}")
            if (filter.isEmpty()) {
                list.add(data)
            } else {
                val indexOf = list.map { it.day }.indexOf(data.day)
                KLog.e("yxs", "查询月份：$data === $indexOf")
                if (indexOf > -1)
                    list[indexOf] = data
            }
        } else {
            list.add(data)
        }
    }

    private fun initTime() {
        //计算月份
        val year = Utils.getYear()
        val month = Utils.getMonth()
        val firstYear = YxsSpUtils.getInt(Constant.FIRST_ENTER_APP_YEAR, year)
        val firstMonth = YxsSpUtils.getInt(Constant.FIRST_ENTER_APP_MONTH, month)
        //如果年数一样 那就计算月数，如果月数一样就是这个月到年底 如果不一样 就是进入App月份到年底
        val i = (year - firstYear + 1) * 12
        KLog.e("yxs", "计算的月份：" + i + "===${(year - firstYear + 1) * 12}")
        val data = mutableListOf<YearBean>()
        for (j in 1..i) {
            KLog.e("yxs", "循环次数：" + i + "===$firstYear")
            val index = (j % 12).let { if (it == 0) 12 else it }
            val calcYear =
                firstYear + (j / 12).let { if (j % 12 == 0 && it > 0) it - 1 else it } //计算出来的年份
            if (calcYear == year && index == month)
                nowMonthIndex = j - 1
            data.add(
                YearBean(
                    calcYear,
                    index,
                    if (nowMonthIndex == j) recordSql?.getData(calcYear, index) else mutableListOf()
                )
            )
        }

        //先插入本月以后的数据，然后延迟插入过往的数据
        if (nowMonthIndex > 0) {
            val nowDataList = mutableListOf<YearBean>()
            for (j in nowMonthIndex until data.size) {
                nowDataList.add(data[j])
            }
            mAdapter.updateList(nowDataList)
        } else {
            mAdapter.updateList(data)
        }

        DefaultHandler.getInstance().postDelayed({
            for (j in 0 until nowMonthIndex) {
                mAdapter.add(data = data[nowMonthIndex - j - 1], index = 0)
            }
        }, 1000)
    }

    private fun setCurrent(index: Int) {
        Main_Page.setCurrentItem(index, true)
    }

    //接收答题卡题号
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(message: MessageEvent) {
        when (message.tag) {
            EventTags.EDIT_COLOR_UPDATE_MAIN_COLOR_LIST -> {
                colorDialog.setUpdate()
            }
        }
    }

    private fun requestSdPermission(code: Int = 10, ret: () -> Unit) {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M
            && ContextCompat.checkSelfPermission(
                mActivity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                mActivity,
                arrayOf(
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE
                ),
                code
            )
        } else {
            ret.invoke()
        }
    }


    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        if (requestCode == 10) {
            KLog.e("yxs", "请求权限返回：$requestCode ===${permissions.size} ===${grantResults.size}")
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                FunctionUtils.downloadApk(mActivity, apk)
            } else {
                Utils.showToast("权限未授予，操作无法继续！")
            }
        }
    }

    private var firstTime = 0L
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (firstTime != 0L) {
                val secondTime = System.currentTimeMillis()
                if (secondTime - firstTime < 2000) {
                    finish()
                }
            }
            firstTime = System.currentTimeMillis()
            Utils.showToast("再按一次退出哦～")
            true
        } else
            super.onKeyDown(keyCode, event)
    }


    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }

}
